﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Fuse8.ContentManagementFramework.SystemFacade.Common
{
    public static class CmsExtensionManager
    {
        public static void LoadExtensions<T>(T entity)
        {
            var catalog = new AggregateCatalog();
            var binDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "bin\\");
            var files = binDir.GetFiles("Fuse8.ContentManagementFramework*.dll", SearchOption.AllDirectories).ToList();

            foreach (var pattern in FilePatterns.Split(';'))
            {
                files.AddRange(binDir.GetFiles(pattern, SearchOption.AllDirectories));
            }

            foreach (var file in files)
            {
                catalog.Catalogs.Add(new AssemblyCatalog(Assembly.LoadFrom(file.FullName)));
            }
            using (var container = new CompositionContainer(catalog))
            {
                container.ComposeParts(entity);
            }
        }

        private static string FilePatterns
        {
            get { return ConfigurationManager.AppSettings["CMS::ExtensionsPattern"] ?? ""; }
        }
    }
}